<template>
  <el-dialog
    title="AI智能创建应付账单"
    :visible.sync="dialogVisible"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="ai-payment-dialog">
      <!-- 采购单信息展示 -->
      <el-card v-if="purchaseInfo" shadow="never" class="purchase-info-card">
        <div slot="header">
          <i class="el-icon-document" />
          <span>关联采购单信息</span>
        </div>
        <el-descriptions :column="2" size="small" border>
          <el-descriptions-item label="订单号">{{ purchaseInfo.order_no }}</el-descriptions-item>
          <el-descriptions-item label="订单名称">{{ purchaseInfo.order_name }}</el-descriptions-item>
          <el-descriptions-item label="供应商">{{ purchaseInfo.supplier_name }}</el-descriptions-item>
          <el-descriptions-item label="币种">{{ purchaseInfo.currency }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!--AI输入区域 -->
      <el-card shadow="never" class="input-card" style="margin-top: 15px;">
        <div slot="header">
          <i class="el-icon-edit-outline" style="color: #1EB7E6;" />
          <span>输入付款信息（支持随意输入）</span>
        </div>

        <!-- 文本输入 -->
        <el-input
          v-model="userInput"
          type="textarea"
          :rows="4"
          placeholder="随意输入付款相关信息，例如：&#10;&#10;今天付了5000美元定金给XX供应商，支付宝转账，流水号123456&#10;&#10;或直接粘贴付款截图中的文字&#10;&#10;AI会自动识别并提取结构化信息"
        />

        <!-- 图片上传 -->
        <div class="upload-section">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleImageChange"
            :file-list="imageList"
            :limit="3"
          >
            <i class="el-icon-plus" />
            <div slot="tip" class="el-upload__tip">
              上传付款截图，AI自动识别图中信息（最多3张）
            </div>
          </el-upload>
        </div>

        <!-- AI分析按钮 -->
        <div style="text-align: center; margin-top: 15px;">
          <el-button
            type="primary"
            icon="el-icon-magic-stick"
            :loading="aiLoading"
            style="background-color: #1EB7E6; border-color: #1EB7E6;"
            @click="extractWithAI"
          >
            AI智能识别
          </el-button>
        </div>
      </el-card>

      <!-- AI提取结果 -->
      <el-card v-if="extracted" shadow="never" class="result-card" style="margin-top: 15px;">
        <div slot="header">
          <i class="el-icon-success" style="color: #67C23A;" />
          <span>AI识别结果（请确认并修改）</span>
        </div>

        <el-form ref="form" :model="paymentForm" :rules="rules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="付款金额" prop="amount">
                <el-input v-model="paymentForm.amount" placeholder="金额">
                  <template slot="append">{{ paymentForm.currency }}</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="币种" prop="currency">
                <el-select v-model="paymentForm.currency" style="width: 100%;">
                  <el-option label="USD" value="USD" />
                  <el-option label="CNY" value="CNY" />
                  <el-option label="EUR" value="EUR" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="付款日期" prop="payment_date">
                <el-date-picker
                  v-model="paymentForm.payment_date"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%;"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="支付方式" prop="payment_method">
                <el-select v-model="paymentForm.payment_method" placeholder="请选择" style="width: 100%;">
                  <el-option label="银行转账" value="bank_transfer" />
                  <el-option label="信用证" value="letter_of_credit" />
                  <el-option label="PayPal" value="paypal" />
                  <el-option label="西联汇款" value="western_union" />
                  <el-option label="支付宝" value="alipay" />
                  <el-option label="微信支付" value="wechat" />
                  <el-option label="现金" value="cash" />
                  <el-option label="其他" value="other" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="交易流水号">
            <el-input v-model="paymentForm.transaction_no" placeholder="银行流水号或第三方交易号" />
          </el-form-item>

          <el-form-item label="收款账号">
            <el-input v-model="paymentForm.payee_account" placeholder="供应商收款账号" />
          </el-form-item>

          <el-form-item label="开户银行">
            <el-input v-model="paymentForm.payee_bank" placeholder="供应商开户银行" />
          </el-form-item>

          <el-form-item label="备注">
            <el-input v-model="paymentForm.notes" type="textarea" :rows="2" placeholder="备注信息" />
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <span slot="footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button
        v-if="extracted"
        type="primary"
        :loading="creating"
        @click="confirmCreate"
      >
        确认创建应付账单
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { createPayable } from '@/api/crm/payable'
import request from '@/utils/request'

export default {
  name: 'AIPaymentDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    purchaseData: {
      type: Object,
      default: () => null
    }
  },
  data() {
    return {
      dialogVisible: false,
      userInput: '',
      imageList: [],
      imageFileIds: [],
      aiLoading: false,
      creating: false,
      extracted: false,
      purchaseInfo: null,
      paymentForm: {
        amount: '',
        currency: 'USD',
        payment_date: '',
        payment_method: '',
        transaction_no: '',
        payee_account: '',
        payee_bank: '',
        notes: ''
      },
      rules: {
        amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
        payment_date: [{ required: true, message: '请选择付款日期', trigger: 'change' }],
        payment_method: [{ required: true, message: '请选择支付方式', trigger: 'change' }]
      }
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val && this.purchaseData) {
        this.initPurchaseInfo()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    initPurchaseInfo() {
      if (!this.purchaseData) return

      this.purchaseInfo = {
        purchase_id: this.purchaseData.id,
        order_no: this.purchaseData.crmorder_data.order_no,
        order_name: this.purchaseData.crmorder_data.name,
        supplier_name: this.purchaseData.crmsupplier_data.name,
        currency: this.purchaseData.crmorder_data.currency
      }

      this.paymentForm.currency = this.purchaseInfo.currency
    },

    handleImageChange(file, fileList) {
      this.imageList = fileList
      // 这里需要上传图片到服务器获取file_id
      // 简化处理，实际应调用上传接口
    },

    async extractWithAI() {
      if (!this.userInput.trim() && this.imageList.length === 0) {
        this.$message.warning('请输入付款信息或上传付款截图')
        return
      }

      this.aiLoading = true

      try {
        const response = await request({
          url: '/crm/api/payables/ai-extract/',
          method: 'post',
          data: {
            user_input: this.userInput,
            purchase_id: this.purchaseInfo.purchase_id,
            image_file_ids: this.imageFileIds
          }
        })

        if (response.success) {
          const extracted = response.data.extracted_info

          // 填充表单
          this.paymentForm = {
            amount: extracted.amount || '',
            currency: extracted.currency || this.purchaseInfo.currency,
            payment_date: extracted.payment_date || new Date().toISOString().substr(0, 10),
            payment_method: extracted.payment_method || '',
            transaction_no: extracted.transaction_no || '',
            payee_account: extracted.payee_account || '',
            payee_bank: extracted.payee_bank || '',
            notes: extracted.notes || this.userInput
          }

          this.extracted = true
          this.$message.success('AI识别完成，请确认信息')
        }
      } catch (error) {
        this.$message.error('AI识别失败：' + (error.message || '未知错误'))
      } finally {
        this.aiLoading = false
      }
    },

    confirmCreate() {
      this.$refs.form.validate(valid => {
        if (!valid) return

        this.creating = true

        const data = {
          order_id: this.purchaseData.crmorder_data.id,
          supplier_id: this.purchaseData.crmsupplier_data.id,
          purchase_id: this.purchaseInfo.purchase_id,
          transaction_type: '采购付款',
          amount: this.paymentForm.amount,
          currency: this.paymentForm.currency,
          expected_payment_date: this.paymentForm.payment_date,
          payee_account: this.paymentForm.payee_account,
          payee_bank: this.paymentForm.payee_bank,
          notes: this.paymentForm.notes,
          // 如果已经付款，同时标记为已付款
          transaction_date: this.paymentForm.payment_date,
          payment_method: this.paymentForm.payment_method,
          reference_number: this.paymentForm.transaction_no
        }

        createPayable(data).then(response => {
          if (response.success) {
            this.$message.success('应付账单创建成功')
            this.$emit('created', response.data)
            this.handleClose()
          }
          this.creating = false
        }).catch(() => {
          this.creating = false
        })
      })
    },

    handleClose() {
      this.dialogVisible = false
      this.userInput = ''
      this.imageList = []
      this.imageFileIds = []
      this.extracted = false
      this.paymentForm = {
        amount: '',
        currency: 'USD',
        payment_date: '',
        payment_method: '',
        transaction_no: '',
        payee_account: '',
        payee_bank: '',
        notes: ''
      }
    }
  }
}
</script>

<style scoped>
.ai-payment-dialog {
  max-height: 70vh;
  overflow-y: auto;
}

.purchase-info-card {
  margin-bottom: 15px;
}

.input-card {
  border-left: 4px solid #1EB7E6;
}

.result-card {
  border-left: 4px solid #67C23A;
}

.upload-section {
  margin-top: 15px;
}
</style>
